package com.hualongdata.util.scalaapi

import java.math.BigInteger
import java.security.SecureRandom

import org.apache.commons.codec.digest.DigestUtils

import scala.util.{Random, Try}

/**
  * Created by yangbajing on 16-8-31.
  */
abstract class BaseUtils {
  val random = new SecureRandom()

  def generateSaltAndPassword(originalPassword: String): Tuple2[String, String] = {
    val salt = randomString(12)
    val password = DigestUtils.sha256Hex(salt + originalPassword)
    (salt, password)
  }

  def randomString(length: Int): String = {
    val upBound = Utils.RANDOM_STRS.length
    (0 until length).map(_ => Utils.RANDOM_STRS(random.nextInt(upBound))).mkString
  }

  def randomInt(being: Int, end: Int): Int = {
    var n = 0
    while (n < 100000) {
      n = random.nextInt(999999)
    }

    n
  }

  def matchPassword(salt: String, encryptedPassword: String, originalPassword: String): Boolean = {
    saltSecretPassword(salt, originalPassword) == encryptedPassword
  }

  def saltSecretPassword(salt: String, originalPassword: String): String = {
    DigestUtils.sha256Hex(salt + originalPassword)
  }

  def parseInt(value: Any): Int = value match {
    case v: String => Integer.parseInt(v)
    case i: Int => i
    case l: Long => l.toInt
    case d: Double => d.toInt
    case bi: BigInt => bi.intValue()
    case bi: BigInteger => bi.intValue()
  }

  def parseInt(value: Any, deft: Int): Int = Try(parseInt(value)).getOrElse(deft)

  def parseLong(value: Any): Long = value match {
    case v: String => java.lang.Long.parseLong(v)
    case i: Int => i.toLong
    case l: Long => l
    case d: Double => d.toLong
    case bi: BigInteger => bi.longValue()
    case bi: BigInt => bi.longValue()
  }

  def parseLong(value: Any, deft: Long): Long = Try(parseLong(value)).getOrElse(deft)
}

object Utils extends BaseUtils {
  val RANDOM_STRS = ('a' to 'z') ++ ('A' to 'Z') ++ ('0' to '9')
}
